package com.roamcattery.plugins.util;

import com.alibaba.fastjson.JSONArray;

import java.util.Collection;
import java.util.Map;
import java.util.function.Function;

/**
 * @author wangwc@wumart.com
 * @version v1.0.0
 * @date 2021/6/7 10:39
 */
public class CollectionUtils {

    public static Boolean isEmpty(Map map){
        return map == null || map.entrySet().size() == 0;
    }

    public static Boolean isNotEmpty(Map map){
        return map != null && map.entrySet().size() > 0;
    }

    public static Boolean isNotEmpty(JSONArray jsonArray){
        return jsonArray != null && jsonArray.size() > 0;
    }

    public static Boolean isEmpty(Collection collection){
        return collection == null || collection.size() == 0;
    }
    public static Boolean isNotEmpty(Collection collection){
        return collection != null && collection.size() > 0;
    }

    /**
     * 用来过渡下Jdk1.8下ConcurrentHashMap的性能bug
     * https://bugs.openjdk.java.net/browse/JDK-8161372
     *
     * @param concurrentHashMap ConcurrentHashMap 没限制类型了，非ConcurrentHashMap就别调用这方法了
     * @param key               key
     * @param mappingFunction   function
     * @param <K>               k
     * @param <V>               v
     * @return V
     * @since 3.4.0
     */
    public static <K, V> V computeIfAbsent(Map<K, V> concurrentHashMap, K key, Function<? super K, ? extends V> mappingFunction) {
        V v = concurrentHashMap.get(key);
        if (v != null) {
            return v;
        }
        return concurrentHashMap.computeIfAbsent(key, mappingFunction);
    }
}
